package com.zhang.gulimall.cart.interceptor;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.zhang.gulimall.cart.service.CartService;
import com.zhang.gulimall.cart.vo.UserInfoTo;
import com.zhang.gulimall.common.vo.GiteeUser;
import jdk.nashorn.internal.ir.CaseNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
public class CartInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Autowired
    CartService cartService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfo = new UserInfoTo();
        HttpSession session = request.getSession();
        GiteeUser user = (GiteeUser) session.getAttribute("loginUser");
        if (user == null) { // 用户是非登录状态
            // 判断是否设置过cookie
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                List<Cookie> collect = Arrays.stream(cookies).filter(c -> c.getName().equals("user-key")).collect(Collectors.toList());
                if (collect.size() > 0) {
                    return true;
                }
            }
            // 没有cookie 设置临时key
            String s = UUID.randomUUID().toString();
            userInfo.setUserKey(s);
            Cookie cookie = new Cookie("user-key", s);
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);
        }
        return true;
    }

    /**
     * 目标方法执行后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
